//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, Descriptions, List, message, Modal, Popover, Space, Table } from "antd";
import { useSeaOtterStores } from "../store";
import { MoreOutlined, RollbackOutlined } from "@ant-design/icons";
import type { ImageReference, ManifestItem } from "@/api/seaotter/image";
import { list_reference, remove_reference } from "@/api/seaotter/image";
import { get_session, get_user_id } from "@/api/user";
import { gen_access_token } from "@/api/project_server";
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import moment from "moment";
import { writeText } from "@tauri-apps/api/clipboard";

const PAGE_SIZE = 10;

const ImageTagList = () => {
    const appStore = useSeaOtterStores();

    const [tagInfoList, setTagInfoList] = useState<ImageReference[]>([]);
    const [tocalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [detailManifest, setDetailManifest] = useState<ManifestItem | null>(null);

    const [canRemove, setCanRemove] = useState(false);
    const [removeTagId, setRemoveTagId] = useState("");

    const calcRemovePerm = async () => {
        if (appStore.curImageGroup == null) {
            setCanRemove(false);
            return;
        }

        const prjPerm = appStore.curImageGroup.perm_info.member_perm[appStore.projectId];
        if (prjPerm == undefined || prjPerm == null) {
            setCanRemove(false);
            return;
        }

        const myUserId = await get_user_id();
        setCanRemove(prjPerm.member_user_id_for_remove.includes(myUserId));
    };

    const loadTagInfoList = async () => {
        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const listRes = await request(list_reference(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: appStore.curImageGroup.group_name,
            image_name: appStore.curImage,
            load_manifest: true,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(listRes.total_count);
        setTagInfoList(listRes.reference_list);
    };

    const removeReference = async () => {
        if (removeTagId == "") {
            return;
        }

        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(remove_reference(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: appStore.curImageGroup.group_name,
            image_name: appStore.curImage,
            reference: removeTagId,
        }));
        message.info("删除成功");
        await loadTagInfoList();
        setRemoveTagId("");
    };

    const columns: ColumnsType<ManifestItem> = [
        {
            title: "硬件架构",
            dataIndex: "architecture",
        },
        {
            title: "操作系统",
            dataIndex: "os",
        },
        {
            title: "存储空间",
            render: (_, row: ManifestItem) => {
                let totalSize = 0;
                for (const layer of row.manifest.layers) {
                    totalSize += layer.size;
                }
                if (totalSize < 1024) {
                    return `${totalSize}B`;
                }

                totalSize /= 1024;
                if (totalSize < 1024) {
                    return `${totalSize.toFixed(1)}K`;
                }

                totalSize /= 1024;
                if (totalSize < 1024) {
                    return `${totalSize.toFixed(1)}M`;
                }
                totalSize /= 1024;
                if (totalSize < 1024) {
                    return `${totalSize.toFixed(1)}G`;
                }
                return "";
            }
        },
        {
            title: "创建时间",
            render: (_, row: ManifestItem) => moment(row.manifest.config.created).format("YYYY-MM-DD HH:mm:ss"),
        },
        {
            title: "",
            width: 80,
            render: (_, row: ManifestItem) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.stopPropagation();
                    setDetailManifest(row);
                }}>查看详情</a>
            )
        }
    ];


    useEffect(() => {
        if (appStore.curImage != "") {
            loadTagInfoList();
        }
    }, [curPage, appStore.curImage]);

    useEffect(() => {
        if (appStore.curImageGroup != null) {
            calcRemovePerm();
        }
    }, [appStore.curImageGroup]);

    return (
        <>
            <Card title={
                <Space>
                    <Button type="link" icon={<RollbackOutlined />} title="返回镜像信息列表"
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            appStore.curImage = "";
                        }} />
                    {appStore.curImage}
                </Space>
            } bordered={false} headStyle={{ backgroundColor: "#eee" }} bodyStyle={{ height: "calc(100vh - 100px)", overflowY: "scroll" }}>
                {appStore.curImageGroup != null && (
                    <List rowKey="reference" dataSource={tagInfoList}
                        pagination={{ total: tocalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false, hideOnSinglePage: true }}
                        renderItem={tagInfo => (
                            <List.Item>
                                <Card title={`${tagInfo.reference}  (${tagInfo.digest})`} style={{ width: "100%" }} bordered={false}
                                    extra={
                                        <Space>
                                            <span>{moment(tagInfo.time_stamp).format("YYYY-MM-DD HH:mm:ss")}</span>
                                            <Popover placement="left" trigger="hover" content={
                                                <Space>
                                                    <span style={{ fontSize: "16px" }}>docker pull {appStore.domainInfo?.domain ?? ""}/{tagInfo.group_name}/{tagInfo.image_name}:{tagInfo.reference}</span>
                                                    <a style={{ fontSize: "16px" }}
                                                        onClick={e => {
                                                            e.stopPropagation();
                                                            e.preventDefault();
                                                            writeText(`docker pull ${appStore.domainInfo?.domain ?? ""}/${tagInfo.group_name}/${tagInfo.image_name}:${tagInfo.reference}`);
                                                            message.info("复制成功");
                                                        }}>复制命令</a>
                                                </Space>
                                            }>
                                                <span style={{ fontSize: "14px", fontWeight: 600, color: "blue" }}>pull</span>
                                            </Popover>
                                            {canRemove && (
                                                <Popover placement="bottom" trigger="click" content={
                                                    <Space direction="vertical">
                                                        <Button type="link" danger onClick={e => {
                                                            e.stopPropagation();
                                                            e.preventDefault();
                                                            setRemoveTagId(tagInfo.reference);
                                                        }}>删除</Button>
                                                    </Space>
                                                }>
                                                    <MoreOutlined />
                                                </Popover>
                                            )}
                                        </Space>
                                    }>
                                    <Table rowKey={row => `${row.architecture}:${row.os}`} dataSource={tagInfo.manifest_info.manifests} columns={columns} pagination={false} />
                                </Card>
                            </List.Item>
                        )} />
                )}
            </Card>

            {detailManifest != null && (
                <Modal open title="详情" mask={false} footer={null}
                    bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll" }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setDetailManifest(null);
                    }}>
                    <Descriptions column={1} bordered labelStyle={{ width: "100px" }}>
                        <Descriptions.Item label="用户">
                            {detailManifest.manifest.config.config.user}
                        </Descriptions.Item>
                        <Descriptions.Item label="网络端口">
                            {JSON.stringify(detailManifest.manifest.config.config.exposed_ports, null, 2)}
                        </Descriptions.Item>
                        <Descriptions.Item label="环境变量">
                            <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>
                                {detailManifest.manifest.config.config.env.join("\n")}
                            </pre>
                        </Descriptions.Item>
                        <Descriptions.Item label="EntryPoint">
                            {detailManifest.manifest.config.config.entrypoint.join(" ")}
                        </Descriptions.Item>
                        <Descriptions.Item label="Cmd">
                            {detailManifest.manifest.config.config.cmd.join(" ")}
                        </Descriptions.Item>
                        <Descriptions.Item label="挂载卷">
                            {JSON.stringify(detailManifest.manifest.config.config.volumes, null, 2)}
                        </Descriptions.Item>
                        <Descriptions.Item label="工作目录">
                            {detailManifest.manifest.config.config.working_dir}
                        </Descriptions.Item>
                        <Descriptions.Item label="标签">
                            {JSON.stringify(detailManifest.manifest.config.config.labels, null, 2)}
                        </Descriptions.Item>
                    </Descriptions>
                </Modal>
            )}

            {removeTagId != "" && (
                <Modal open title={`删除版本`} mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveTagId("");
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeReference();
                    }}>
                    是否删除版本&nbsp;{removeTagId}&nbsp;?
                </Modal>
            )}
        </>
    );
};

export default observer(ImageTagList);